package view.pakn;

import java.io.File;

import java.io.FileInputStream;
import java.io.OutputStream;

import java.util.ArrayList;
import java.util.List;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;

import javax.faces.application.Application;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCIteratorBinding;
import oracle.adf.view.rich.component.UIXTable;
import oracle.adf.view.rich.component.rich.RichPopup;
import oracle.adf.view.rich.component.rich.input.RichSelectBooleanCheckbox;
import oracle.adf.view.rich.component.rich.nav.RichCommandButton;
import oracle.adf.view.rich.component.rich.output.RichOutputText;
import oracle.adf.view.rich.context.AdfFacesContext;
import oracle.adf.view.rich.event.DialogEvent;
import oracle.adf.view.rich.event.PopupCanceledEvent;

import oracle.binding.BindingContainer;

import oracle.jbo.Row;
import oracle.jbo.ViewCriteria;
import oracle.jbo.ViewObject;
import oracle.jbo.server.ViewRowImpl;
import oracle.jbo.uicli.binding.JUCtrlHierNodeBinding;
import oracle.jbo.uicli.binding.JUCtrlRangeBinding;

import org.apache.myfaces.trinidad.event.SelectionEvent;
import org.apache.myfaces.trinidad.model.UploadedFile;
import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import org.apache.myfaces.trinidad.util.Service;

import oracle.jbo.RowSet;

import view.common.Utils;

public class phananhkiennghiBean {
    private RichPopup popupThemMoi;
    private RichPopup popupDelete;
    private UploadedFile _file;
    private RichOutputText inputtextOperator;
    private String Hoten;
    private String Noidung;
    private String tieude;
    private String Email;
    private UIXTable tbl;
    private RichCommandButton buttonDownload;
    private int pageNumber;
    private static final int RANGE_SIZE = 10;

    public phananhkiennghiBean() {
        JUCtrlRangeBinding PAKNView = this.getPAKNView();
        PAKNView.getIteratorBinding().getNavigatableRowIterator().scrollRange(0);

        if (Boolean.FALSE.equals(Utils.getElExpression("#{adfFacesContext.postback}"))) {
            DCIteratorBinding iter1 =
                Utils.getIteratorBinding("PhanAnhKienNghiView1Iterator");
            iter1.getViewObject().getViewCriteriaManager().clearViewCriterias();
            iter1.executeQuery();
        }
    }

    public BindingContainer getBindings() {
        return BindingContext.getCurrent().getCurrentBindingsEntry();
    }

    public void setPopupThemMoi(RichPopup popupThemMoi) {
        this.popupThemMoi = popupThemMoi;
    }

    public RichPopup getPopupThemMoi() {
        return popupThemMoi;
    }

    public void create(ActionEvent actionEvent) {
        Utils.execute("CreateInsert");
        Utils.showPopup(popupThemMoi);
        inputtextOperator.setValue("0");
    }

    public void update(ActionEvent actionEvent) {
        Utils.showPopup(popupThemMoi);
        inputtextOperator.setValue("1");
    }

    public void downloadfile(ActionEvent actionEvent) {
        String fileName =
            (String)actionEvent.getComponent().getAttributes().get("fileName");
        buttonDownload.setText(fileName);
        FacesContext context = FacesContext.getCurrentInstance();
        ExtendedRenderKitService erks =
            Service.getService(context.getRenderKit(),
                               ExtendedRenderKitService.class);

        erks.addScript(context, "customHandler();");

    }

    public void dwdFile(FacesContext facesContext, OutputStream out) {
        File duongdan =
            new File(Utils.ENUM_CAU_HINH_KHOA.FILE_ROOT.getValue("HtCauHinhView1Iterator"),
                     Utils.ENUM_CAU_HINH_KHOA.PAKN_DIR.getValue("HtCauHinhView1Iterator"));
        File file = new File(duongdan + "/" + buttonDownload.getText());
        FileInputStream Fileinput = null;
        byte[] bt;
        try {
            Fileinput = new FileInputStream(file);
            int checkline;
            while ((checkline = Fileinput.available()) > 0) {
                bt = new byte[checkline];
                int rst = Fileinput.read(bt);
                out.write(bt, 0, bt.length);
                if (rst == -1)
                    break;

            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void ResetSearch() {
        try {
            DCIteratorBinding iter1 =
                Utils.getIteratorBinding("PhanAnhKienNghiView1Iterator");
            iter1.getViewObject().getViewCriteriaManager().clearViewCriterias();
            iter1.executeQuery();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void search() {
        try {
            DCIteratorBinding IteratorPAKN =
                Utils.getIteratorBinding("PhanAnhKienNghiView1Iterator");
            ViewObject vo = IteratorPAKN.getViewObject();
            ViewCriteria vc =
                vo.getViewCriteriaManager().getViewCriteria("PhanAnhKienNghiViewCriteria");
            vo.ensureVariableManager().setVariableValue("varTieude",
                                                        getTieude());
            vo.ensureVariableManager().setVariableValue("varEmail",
                                                        getEmail());
            vo.ensureVariableManager().setVariableValue("varHoten",
                                                        getHoten());
            vo.ensureVariableManager().setVariableValue("varNoidung",
                                                        getNoidung());
            vo.getViewCriteriaManager().removeViewCriteria("PhanAnhKienNghiViewCriteria");
            vo.getViewCriteriaManager().applyViewCriteria(vc);
            IteratorPAKN.executeQuery();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void commitDialog(DialogEvent dialogEvent) {
        try {
            int operator = inputtextOperator.getValue().equals("1") ? 1 : 0;
            Boolean successUploaded = true;
            File filePath =
                new File(Utils.ENUM_CAU_HINH_KHOA.FILE_ROOT.getValue("HtCauHinhView1Iterator"),
                         Utils.ENUM_CAU_HINH_KHOA.PAKN_DIR.getValue("HtCauHinhView1Iterator"));
            File duongdantuongdoi =
                new File(Utils.ENUM_CAU_HINH_KHOA.PAKN_DIR.getValue("HtCauHinhView1Iterator"));
            Object fileId = null;
            DCIteratorBinding detailIterator1 =
                Utils.getIteratorBinding("PhanAnhKienNghiView1Iterator");
            DCIteratorBinding fileIterator1 =
                Utils.getIteratorBinding("HtFileView1Iterator");
            if (this.getFile() != null) {
                if (operator == 1) {
                    fileId =
                            detailIterator1.getCurrentRow().getAttribute("FileId");
                    if (fileId == null) {
                        Utils.execute("HtFileInsert");
                        fileId =
                                fileIterator1.getCurrentRow().getAttribute("Id").toString();
                    }
                } else {
                    Utils.execute("HtFileInsert");
                    fileId =
                            fileIterator1.getCurrentRow().getAttribute("Id").toString();
                }
                if (Utils.fileUpload(this.getFile(), filePath,
                                     fileId.toString())) {
                    Utils.processUpload(this.getFile(), duongdantuongdoi,
                                        "HtFileView1Iterator",
                                        "PhanAnhKienNghiView1Iterator",
                                        operator, Utils.ENUM_MA_UNG_DUNG.PAKN,
                                        fileId.toString());
                } else {
                    successUploaded = false;
                }
            }

            if (successUploaded) {
                Utils.execute("Commit");
                Utils.iteratorRefresh("PhanAnhKienNghiView1Iterator");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void cancelDiaglog(PopupCanceledEvent popupCanceledEvent) {
        Utils.execute("Rollback");
    }

    public void deleteDiaglog(DialogEvent dialogEvent) {
        try {
            if (Utils.getIteratorBinding("PhanAnhKienNghiView1Iterator").getCurrentRow() ==
                null) {
                String meg = "Không có dữ liệu.";
                Utils.showMessage(Utils.MSG_INFO, meg);
            } else {
                DCIteratorBinding iterPhananhkiennghi =
                    Utils.getIteratorBinding("PhanAnhKienNghiView1Iterator");
                String PaknId =
                    iterPhananhkiennghi.getCurrentRow().getAttribute("Id").toString();
                ViewObject vo = iterPhananhkiennghi.getViewObject();
                vo.setAccessMode(RowSet.SCROLLABLE);
                iterPhananhkiennghi.setCurrentRowWithKeyValue(PaknId);
                if (iterPhananhkiennghi.getCurrentRow().getAttribute("FileId") !=
                    null) {
                    DCIteratorBinding iterHtFile =
                        Utils.getIteratorBinding("HtFileView1Iterator");
                    File filePath =
                        new File(Utils.ENUM_CAU_HINH_KHOA.FILE_ROOT.getValue("HtCauHinhView1Iterator"),
                                 "/");
                    String FileId =
                        iterPhananhkiennghi.getCurrentRow().getAttribute("FileId").toString();
                    iterHtFile.setCurrentRowWithKeyValue(FileId);
                    String duongdan =
                        iterHtFile.getCurrentRow().getAttribute("DuongDan").toString();
                    File oldPath = new File(filePath, duongdan);
                    Utils.fileDelete(oldPath);
                    // Xoa trong bang Ht_File
                    iterHtFile.removeCurrentRow();
                }
                Utils.execute("Delete");
                Utils.execute("Commit");
                vo.setAccessMode(RowSet.RANGE_PAGING);
                Utils.iteratorRefresh("PhanAnhKienNghiView1Iterator");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    //    public void deleteDiaglog(DialogEvent dialogEvent) {
    //        try {
    //            if (Utils.getIteratorBinding("PhanAnhKienNghiView1Iterator").getCurrentRow() ==
    //                null) {
    //                String meg = "Không có dữ liệu.";
    //                Utils.showMessage(Utils.MSG_INFO, meg);
    //            } else {
    //                DCIteratorBinding iterPhananhkiennghi =
    //                    Utils.getIteratorBinding("PhanAnhKienNghiView1Iterator");
    //                String PaknId =
    //                    iterPhananhkiennghi.getCurrentRow().getAttribute("Id").toString();
    //                ViewObject vo = iterPhananhkiennghi.getViewObject();
    //                vo.setAccessMode(RowSet.SCROLLABLE);
    //                iterPhananhkiennghi.setCurrentRowWithKeyValue(PaknId);
    //                if (tbl.getSelectedRowKeys().size() > 0) {
    //                    for (Object facesRowKey : tbl.getSelectedRowKeys()) {
    //                        tbl.setRowKey(facesRowKey);
    //                        Object objrow = tbl.getRowData();
    //                        if (objrow == null) {
    //                            String meg = "Không có dữ liệu";
    //                            Utils.showMessage(Utils.MSG_INFO, meg);
    //                        } else {
    //                            JUCtrlHierNodeBinding rowData =
    //                                (JUCtrlHierNodeBinding)objrow;
    //                            Row row = rowData.getRow();
    //                            if (row.getAttribute("FileId") != null) {
    //                                DCIteratorBinding iterHtFile =
    //                                    Utils.getIteratorBinding("HtFileView1Iterator");
    //                                File filePath =
    //                                    new File(Utils.ENUM_CAU_HINH_KHOA.FILE_ROOT.getValue("HtCauHinhView1Iterator"),
    //                                             "/");
    //                                String FileId =
    //                                    row.getAttribute("FileId").toString();
    //                                iterHtFile.setCurrentRowWithKeyValue(FileId);
    //                                String duongdan =
    //                                    iterHtFile.getCurrentRow().getAttribute("DuongDan").toString();
    //                                File oldPath = new File(filePath, duongdan);
    //                                Utils.fileDelete(oldPath);
    //                                // Xoa trong bang Ht_File
    //                                iterHtFile.removeCurrentRow();
    //                            }
    //                            ViewRowImpl viewRow = (ViewRowImpl)row;
    //                            String key =
    //                                viewRow.getKey().toStringFormat(false);
    //                            iterPhananhkiennghi.removeRowWithKey(key);
    //                        }
    //
    //                    }
    //                    Utils.execute("Commit");
    //                } else {
    //                    String meg = "Bạn chưa chọn bản ghi nào.";
    //                    Utils.showMessage(Utils.MSG_INFO, meg);
    //                }
    //                vo.setAccessMode(RowSet.RANGE_PAGING);
    //                Utils.iteratorRefresh("PhanAnhKienNghiView1Iterator");
    //                //                boolean b = false;
    //                //                for (int i = 0;
    //                //                     i < iterPhananhkiennghi.getEstimatedRowCount();
    //                //                     i++) {
    //                //                    Row row = iterPhananhkiennghi.getRowAtRangeIndex(i);
    //                //                    if (true == row.getAttribute("SelectedRow")) {
    //                //                        b = true;
    //                //                        if (row.getAttribute("FileId") != null) {
    //                //                            DCIteratorBinding iterHtFile =
    //                //                                Utils.getIteratorBinding("HtFileView1Iterator");
    //                //                            File filePath =
    //                //                                new File(Utils.ENUM_CAU_HINH_KHOA.FILE_ROOT.getValue("HtCauHinhView1Iterator"),
    //                //                                         "/");
    //                //                            String FileId =
    //                //                                row.getAttribute("FileId").toString();
    //                //                            iterHtFile.setCurrentRowWithKeyValue(FileId);
    //                //                            String duongdan =
    //                //                                iterHtFile.getCurrentRow().getAttribute("DuongDan").toString();
    //                //                            File oldPath = new File(filePath, duongdan);
    //                //                            Utils.fileDelete(oldPath);
    //                //                            // Xoa trong bang Ht_File
    //                //                            iterHtFile.removeCurrentRow();
    //                //                        }
    //                //                        row.remove();
    //                //                        Utils.execute("Commit");
    //                //                    } else {
    //                //                        b = false;
    //                //                    }
    //                //                }
    //                //                if (b == false) {
    //                //                    Utils.showMessage(Utils.MSG_INFO,
    //                //                                      "Bạn chưa chọn bản ghi nào.");
    //                //                }
    //            }
    //        } catch (Exception ex) {
    //            ex.printStackTrace();
    //        }
    //    }

    public void openPopupDelete(ActionEvent actionEvent) {
        if (Utils.getIteratorBinding("PhanAnhKienNghiView1Iterator").getCurrentRow() ==
            null) {
            String messageText = "Chưa có phản ánh kiến nghị nào.";
            Utils.showMessage(Utils.MSG_INFO, messageText);
        } else {
            Utils.showPopup(popupDelete);
        }
    }

    public void rowSelected(SelectionEvent se) {
        Utils.rowSelected(se, "PhanAnhKienNghiView1");
    }

    public String goToPage() {
        Utils.goToPage(RANGE_SIZE, pageNumber, "PhanAnhKienNghiView1");
        return null;
    }

    public String goLastPage() {
        Utils.goLastPage(RANGE_SIZE, "PhanAnhKienNghiView1");
        return null;
    }

    public boolean isLastEnabled() {
        return Utils.isLastEnabled(RANGE_SIZE, "PhanAnhKienNghiView1");
    }

    public boolean isFirstEnabled() {
        return Utils.isFirstEnabled(RANGE_SIZE, "PhanAnhKienNghiView1");
    }
    
    private JUCtrlRangeBinding getPAKNView() {
        return Utils.getViewObject("PhanAnhKienNghiView1");
    }

    public void setFile(UploadedFile _file) {
        this._file = _file;
    }

    public UploadedFile getFile() {
        return _file;
    }

    public void setInputtextOperator(RichOutputText inputtextOperator) {
        this.inputtextOperator = inputtextOperator;
    }

    public RichOutputText getInputtextOperator() {
        return inputtextOperator;
    }

    public void setTieude(String tieude) {
        this.tieude = tieude;
    }

    public String getTieude() {
        return tieude;
    }

    public void setEmail(String Email) {
        this.Email = Email;
    }

    public String getEmail() {
        return Email;
    }

    public void setTbl(UIXTable tbl) {
        this.tbl = tbl;
    }

    public UIXTable getTbl() {
        return tbl;
    }

    public void setButtonDownload(RichCommandButton buttonDownload) {
        this.buttonDownload = buttonDownload;
    }

    public RichCommandButton getButtonDownload() {
        return buttonDownload;
    }

    public void setHoten(String Hoten) {
        this.Hoten = Hoten;
    }

    public String getHoten() {
        return Hoten;
    }

    public void setNoidung(String Noidung) {
        this.Noidung = Noidung;
    }

    public String getNoidung() {
        return Noidung;
    }

    public void setPageNumber(int pageNumber) {
        JUCtrlRangeBinding PAKNView = this.getPAKNView();
        if (pageNumber >
            Math.max(1, (PAKNView.getIteratorBinding().getEstimatedRowCount() -
                         1) / RANGE_SIZE + 1)) {
            pageNumber =
                    (int)Math.max(1, (PAKNView.getIteratorBinding().getEstimatedRowCount() -
                                      1) / RANGE_SIZE + 1);
        }
        this.pageNumber = pageNumber;
    }

    public int getPageNumber() {
        return pageNumber =
                getPAKNView().getIteratorBinding().getNavigatableRowIterator().getRangeStart() /
                RANGE_SIZE + 1;
    }

    public static int getRANGE_SIZE() {
        return RANGE_SIZE;
    }

    public void setPopupDelete(RichPopup popupDelete) {
        this.popupDelete = popupDelete;
    }

    public RichPopup getPopupDelete() {
        return popupDelete;
    }
}
